package com.platform.boot.security.user;

import com.platform.boot.utils.CriteriaUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;

/**
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class UserRequest extends User implements Serializable {

    private String securityCode;

    public UserRequest securityCode(String tenantCode) {
        this.setSecurityCode(tenantCode);
        return this;
    }

    public UserRequest id(Long id) {
        this.setId(id);
        return this;
    }

    public UserRequest buildPassword() {
        this.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder()
                .encode(getPassword()));
        return this;
    }

    public User toUser() {
        User user = new User();
        BeanUtils.copyProperties(this, user);
        return user;
    }

    public Criteria toCriteria() {
        Criteria criteria = CriteriaUtils.build(this, List.of("securityCode"));
        if (StringUtils.hasLength(this.securityCode)) {
            criteria = criteria.and("tenantCode").like(this.securityCode + "%");
        }
        return criteria;
    }

}